'''
@Author Raphael
@License MIT
@CopyLeft Support
@Version 1.0.3
@Language Python3.7
@Start 22 April 2019
@End 21 May 2019
'''
cdb_version = '1.0.3'

#你可以仅仅使用此文件实现canDatabase的全部功能（数据文件除外）
#You can just use this file to implement all the functions of canDatabase(Except for data files)

dataFilePath = 'demo.cdb'		#数据库文件路径
data = ''						#数据库文件内容
titIndex = {}
def dataLoad():								#加载数据
	global data
	file = open(dataFilePath,'r',encoding = 'utf-8')
	data = file.read()

def format():								#格式化数据
	global data
	data = data.split('\n')					#分割字符串，使得每一条记录为数组的一个元素
	if data[len(data)-1] == '':				#去掉某些文件后面的“\n”
		data.remove('')
	temp = []
	for i in range(0, len(data)):
		temp.append(data[i].split('#$#'))
	data = temp

def init():									#初始化，即执行所有必须在使用之前运行的函数
	dataLoad()
	format()
	tit = data[0]
	global titIndex
	for i in range(0,len(tit)):
		titIndex[tit[i]]=i					#索引字典

def Dump(data):								#将已经更改的数据写入硬盘
	temp = []
	for i in range(0,len(data)-1):
		t = '#$#'.join(data[i])
		temp.append(t)
	t = '#$#'.join(data[-1])
	temp.append(t)
	temp = '\n'.join(temp)
	file = open(dataFilePath,'w',encoding = 'utf-8')
	file.write(temp)

def Query(From,Value,Target):				#查询函数，From是查找的列，Value是查找的值，Target是返回值所在列
	fromIndex = titIndex[From]
	tarIndex = titIndex[Target]
	try:
		for i in range(1,len(data)):
			if data[i][fromIndex]==Value:
				return data[i][tarIndex],0
		return 0x0001	#'错误：找不到目标值！'
	except:
		return 0xFFFF	#'未知错误'

def Update(From,Value,Target,newValue):		#更新函数，From是查找的列，Value是查找的值，Target是需要修改的列，newValue是新值
	fromIndex = titIndex[From]
	tarIndex = titIndex[Target]
	for i in range(1,len(data)):
		if data[i][fromIndex]==Value:
			data[i][tarIndex]=newValue
			Dump(data)
			return 0
	return 0x0001	#'错误：找不到目标值'

def Insert(dataList,keyName):				#插入函数，datalist是数据集合，keyName是主键
	if Query(keyName,dataList[titIndex[keyName]],keyName)==dataList[titIndex[keyName]]:
		return 0x0002	#'错误，关键值已存在！'
	global data
	data.append(dataList)
	Dump(data)
	return 0

def Delete(keyID,keyValue):				#删除函数keyID是关键字在元组的下标，keyValue是关键值		
	for i in range(1,len(data)):
		if data[i][keyID]==keyValue:
			del data[i]
			Dump(data)
			return 0
		else:
			return 0x0001	#'错误，找不到目标值'


def Create(fileName,Title):
	if not fileName == "":
		fo = open(fileName,'w',encoding='utf-8')
		fo.write("#$#".join(Title))
		fo.close()
	else:
		return 0x0002	#文件名不存在